package com.ruoyi.cs.service.impl;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.Response;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.cs.domain.*;
import com.ruoyi.cs.domain.vo.TFringeBenefitsGoodsVo;
import com.ruoyi.cs.domain.vo.TFringeBenefitsParam;
import com.ruoyi.cs.domain.vo.TFringeBenefitsVo;
import com.ruoyi.cs.mapper.*;
import com.ruoyi.cs.service.CommonService;
import com.ruoyi.cs.service.ITFringeBenefitsService;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.mapper.SysConfigMapper;
import com.ruoyi.system.service.ISysDictTypeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 福利日常活动业务层处理
 *
 * @author ruoyi
 * @date 2021-03-25
 */
@Service
@SuppressWarnings("all")
public class TFringeBenefitsServiceImpl implements ITFringeBenefitsService {
    private static final Logger log = LoggerFactory.getLogger(TFringeBenefitsServiceImpl.class);
    @Autowired
    private TFringeBenefitsMapper tFringeBenefitsMapper;
    @Autowired
    private ISysDictTypeService iSysDictTypeService;
    @Autowired
    private TUserMapper tUserMapper;
    @Autowired
    private TBalanceChangeMapper tBalanceChangeMapper;
    @Autowired
    private CommonService commonService;
    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private TGoodsPoolMapper tGoodsPoolMapper;
    @Autowired
    private TBackpackMapper tBackpackMapper;


    @Override
    public List<TFringeBenefits> selectTFringeBenefitsList(TFringeBenefits tFringeBenefits) {
        return tFringeBenefitsMapper.selectTFringeBenefitsList(tFringeBenefits);
    }

    @Override
    public BigDecimal selectUserIntegral(String userId, String beginTime, String endTime) {
        return tFringeBenefitsMapper.selectUserIntegral(userId, beginTime, endTime);
    }

    /**
     * 领取记录
     */
    @Override
    public List<TFringeBenefits> receivingRecords(String userId) {
        TFringeBenefits tFringeBenefits = new TFringeBenefits();
        tFringeBenefits.setUserId(userId);
        tFringeBenefits.setDelFlag(Constants.SUCCESS);
        return tFringeBenefitsMapper.receivingRecords(tFringeBenefits);
    }

    /**
     * @Desc: 补偿系统详情
     * @author: zz
     * @date: 2023/12/14
     */
    @Override
    public TFringeBenefitsVo compensateInfo(String userId) {
        Integer unclaimedNum = 0;
        // 获取当前年份和月份
        LocalDate currentDate = LocalDate.now();
        int year = currentDate.getYear();
        int month = currentDate.getMonthValue();

        List<SysDictData> proportionOfPoints = iSysDictTypeService.selectDictDataByType("compensate_radio");
        List<Integer> welfareDates = proportionOfPoints.stream()
                .map(sysDictData -> Integer.parseInt(sysDictData.getDictLabel()))
                .collect(Collectors.toList());

        SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique("min_receive_bc_fee");

        LocalDate startDate = LocalDate.of(year, month, 1);
        LocalDate endDate = startDate.plusMonths(1).minusDays(1);
        LocalDate lastMonthEndDate = startDate.minusDays(1); // 上月月底
        LocalDate lastMonthStartDate = lastMonthEndDate.withDayOfMonth(22); // 上月的22号
        List<TFringeBenefitsParam> paramList = new ArrayList<>();
        for (int i = 0; i < welfareDates.size(); i++) {
            Integer welfareDate = welfareDates.get(i);
            SysDictData sysDictData = proportionOfPoints.stream().filter(bean -> bean.getDictLabel().equals(welfareDate.toString())).findFirst().get();

            LocalDate welfareStart;
            LocalDate welfareEnd;
            if (welfareDate == 1) {
                welfareStart = lastMonthStartDate;
                welfareEnd = lastMonthEndDate;
            } else {
                welfareStart = startDate.withDayOfMonth(welfareDate).minusDays(7);
                welfareEnd = startDate.withDayOfMonth(welfareDate).minusDays(1);
            }
            if (welfareEnd.isAfter(endDate)) {
                welfareEnd = endDate;
            }

            String startTime = welfareStart.toString() + " 00:00:00";
//            if(i==0){
//                startTime = "2024-03-01 00:00:00";
//            }
            String endTime = welfareEnd.toString() + " 23:59:59";
            /**优化后的亏损计算*/
//            BigDecimal currentPoints = tBalanceChangeMapper.countLossValue(userId,startTime,endTime);
            BigDecimal currentPoints = tBackpackMapper.countRangerUserKsFee(userId,startTime,endTime);
            TFringeBenefitsParam param = new TFringeBenefitsParam();
            param.setDateCode(welfareDate);
            param.setKsFee(currentPoints.compareTo(BigDecimal.ZERO) > 0 ? currentPoints : BigDecimal.ZERO);

            BigDecimal bcfee = BigDecimal.ZERO;
            if(currentPoints.compareTo(BigDecimal.ZERO) > 0){
                bcfee = currentPoints.multiply(new BigDecimal(sysDictData.getDictValue()));
            }
            param.setBcFee(bcfee);
            StringBuilder sb = new StringBuilder();
            sb.append(year).append(month).append(welfareDate);
            /**判断是否领取过*/
            long receiveNum = tFringeBenefitsMapper.countReceiveDate(userId,sb.toString());
            if(receiveNum > 0){
                param.setReceiveStatus(1);
            }else {
                if(currentPoints.compareTo(new BigDecimal(sysConfig.getConfigValue())) > 0){
                    param.setReceiveStatus(0);
                    unclaimedNum++;
                }else {
                    param.setReceiveStatus(2);
                }
            }
            paramList.add(param);
        }
        TFringeBenefitsVo tFringeBenefitsVo = new TFringeBenefitsVo();
        tFringeBenefitsVo.setUnclaimedNum(unclaimedNum);
        tFringeBenefitsVo.setParams(paramList);
        return tFringeBenefitsVo;
    }

    /**
     * @Desc: 手动领取
     * @author: zz
     * @date: 2023/12/14
     */
    @Override
    public Response immediatelyReceive(String userId,Integer dateCode) {
        /*查询用户信息*/
        TUser tUser = tUserMapper.selectTUserById(userId);
        if (tUser == null || !Constants.SUCCESS.equals(tUser.getDelFlag())) {
            return Response.fail(Constants.FAILCODE, "用户不存在或已被冻结，请联系管理员！");
        }

        // 获取当前年份和月份
        LocalDate currentDate = LocalDate.now();
        int year = currentDate.getYear();
        int month = currentDate.getMonthValue();
        List<SysDictData> proportionOfPoints = iSysDictTypeService.selectDictDataByType("compensate_radio");
        List<Integer> welfareDates = proportionOfPoints.stream()
                .map(sysDictData -> Integer.parseInt(sysDictData.getDictLabel()))
                .collect(Collectors.toList());

        Optional<Integer> code1 = welfareDates.stream().filter(code -> code.equals(dateCode)).findFirst();
        if(!code1.isPresent()){
            return Response.fail("参数错误！");
        }
        int index = welfareDates.indexOf(dateCode);

        LocalDate startDate = LocalDate.of(year, month, 1);
        LocalDate endDate = startDate.plusMonths(1).minusDays(1);

        LocalDate lastMonthEndDate = startDate.minusDays(1); // 上月月底
        LocalDate lastMonthStartDate = lastMonthEndDate.withDayOfMonth(22); // 上月的22号
        Integer welfareDate = code1.get();
        SysDictData sysDictData = proportionOfPoints.stream().filter(bean -> bean.getDictLabel().equals(welfareDate.toString())).findFirst().get();

        LocalDate welfareStart;
        LocalDate welfareEnd;

        if (welfareDate == 1) {
            welfareStart = lastMonthStartDate;
            welfareEnd = lastMonthEndDate;
        } else {
            welfareStart = startDate.withDayOfMonth(welfareDate).minusDays(7);
            welfareEnd = startDate.withDayOfMonth(welfareDate).minusDays(1);
        }
        if (welfareEnd.isAfter(endDate)) {
            welfareEnd = endDate;
        }
        String startTime = welfareStart.toString() + " 00:00:00";
//        startTime = "2024-03-01 00:00:00";
        String endTime = welfareEnd.toString() + " 23:59:59";

        if(DateUtils.parseDate(startTime).getTime() > DateUtils.getNowDate().getTime()){
            return Response.fail("未到领取开放时间!");
        }

        SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique("min_receive_bc_fee");

        /**优化后的亏损计算*/
//        BigDecimal currentPoints = tBalanceChangeMapper.countLossValue(userId,startTime,endTime);
        BigDecimal currentPoints = tBackpackMapper.countRangerUserKsFee(userId,startTime,endTime);

        BigDecimal bcfee = currentPoints.multiply(new BigDecimal(sysDictData.getDictValue()));
        StringBuilder sb = new StringBuilder();
        sb.append(year).append(month).append(welfareDate);
        /**判断是否领取过*/
        long receiveNum = tFringeBenefitsMapper.countReceiveDate(userId,sb.toString());
        if(receiveNum > 0){
            return Response.fail("您已领取过！");
        }else {
            if(currentPoints.compareTo(new BigDecimal(sysConfig.getConfigValue())) < 0){
                return Response.fail("亏损金额低于最低补偿金额，不符合领取条件！");
            }
        }

        TGoodsPool bean = tGoodsPoolMapper.getClosestPrice(bcfee);
        if(bean == null){
            return Response.fail("没有符合领取的饰品！");
        }
        /*新增领取记录*/
        TFringeBenefits tFringeBenefits1 = new TFringeBenefits();
        tFringeBenefits1.setUserId(userId);
        tFringeBenefits1.setGoldCoins(bean.getGoodsPrice());
        tFringeBenefits1.setIntegral(currentPoints);
        tFringeBenefits1.setClaimType(Constants.CLAIM_TYPE_0);
        tFringeBenefits1.setRewardProportion(new BigDecimal(sysDictData.getDictValue()));
        tFringeBenefits1.setIntegralStage(null);
        tFringeBenefits1.setBalanceBefore(tUser.getUserBalance());
        tFringeBenefits1.setBalanceAfter(tUser.getUserBalance());
        tFringeBenefits1.setCreateTime(DateUtils.getNowDate());
        tFringeBenefits1.setGoodsPoolId(bean.getGoodsId());
        tFringeBenefits1.setReceiveDate(sb.toString());

        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        tFringeBenefits1.setReceiveIP(ip);
        tFringeBenefits1.setReceiveArea(AddressUtils.getRealAddressNameByIP(ip));
        tFringeBenefitsMapper.insertSelective(tFringeBenefits1);

        /**插入背包*/
        String bbId = DateUtils.dateTimeNow() + IdUtils.fastUUID().substring(0, 8);
        TBackpack backpack = new TBackpack();
        backpack.setBbId(bbId);
        backpack.setUserId(userId);
        backpack.setGoodsId(bean.getGoodsId());
        backpack.setOpenBeforeBalance(tUser.getUserBalance());
        backpack.setGoodsBelongingType(Constants.GOOGSBLTYPE15);
        backpack.setOpenBoxPrice(BigDecimal.ZERO);
        backpack.setGoodsBelongingId(tFringeBenefits1.getId().toString());
        backpack.setGoodsBelongingName("补偿系统奖励");
        backpack.setGoodsPrice(bean.getGoodsPrice());
        backpack.setGoodsExprice(bean.getGoodsPrice());
        backpack.setDelFlag(Constants.SUCCESS);
        backpack.setCreateTime(DateUtils.getNowDate());
        backpack.setGoodsType(bean.getGoodsType());
        backpack.setGoodsNum(1);
        backpack.setUserPromotersId(tUser.getUserPromotersId());
        backpack.setAuditStatus(Constants.AUDITSTATUS0);
        backpack.setBbGoodsName(bean.getGoodsName());
        backpack.setBbGoodsPic(bean.getGoodsPic());
        backpack.setBbGoodsGrate(bean.getGoodsGrate());
        backpack.setOpenAfterBalance(tUser.getUserBalance());
        backpack.setBbStatus(Constants.BBSTATUS0);
        backpack.setUserSeed(tUser.getUserSeed());
        backpack.setServerSeed(null);
        backpack.setCommonHash(null);
        backpack.setRollValue(null);
        tBackpackMapper.insertTBackpack(backpack);

        /**记录流水表*/
        TBalanceChange balanceChange = new TBalanceChange();
        balanceChange.setUserId(userId);
        balanceChange.setBalanceBefore(tUser.getUserBalance());
        balanceChange.setBalanceAfter(tUser.getUserBalance());
        balanceChange.setOperationType(Constants.OPERATIONTYPE19);
        balanceChange.setFrequency(1);
        balanceChange.setFee(BigDecimal.ZERO);
        balanceChange.setCorrespondingid(bean.getGoodsId());
        balanceChange.setCreateTime(DateUtils.getNowDate());
        balanceChange.setSecondCurrencyBefore(tUser.getSecondCurrency());
        balanceChange.setSecondCurrencyAfter(tUser.getSecondCurrency());
        balanceChange.setConsumeValue(BigDecimal.ZERO);
        balanceChange.setProfitPrice(bean.getGoodsPrice());
        balanceChange.setCostFee(BigDecimal.ZERO);
        tBalanceChangeMapper.insertTBalanceChange(balanceChange);

        TFringeBenefitsGoodsVo vo = TFringeBenefitsGoodsVo.builder().bbId(bbId)
                .goodsGrate(bean.getGoodsGrate())
                .goodsName(bean.getGoodsName())
                .goodsPic(bean.getGoodsPic())
                .goodsWear(bean.getGoodsWear())
                .goodsPrice(bean.getGoodsPrice()).build();
        return Response.success(vo);
    }

}
